/*
 * Copyright (c) 2012, marco.tamburelli@gmail.com
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met: 
 * 
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer. 
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution. 
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 * 
 * The views and conclusions contained in the software and documentation are those
 * of the authors and should not be interpreted as representing official policies, 
 * either expressed or implied, of the CometMI Project.
 */
package org.cometmi.gwt.server;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebServlet;

import org.apache.log4j.Logger;
import org.cometmi.gwt.client.CometMiService;
import org.cometmi.gwt.server.MiBox.DeferredPoller;
import org.cometmi.gwt.server.async.AsyncManager;
import org.cometmi.gwt.server.async.AsyncRemoteServiceServlet;
import org.cometmi.gwt.shared.exceptions.NameParseException;
import org.cometmi.gwt.shared.request.Call;
import org.cometmi.gwt.shared.request.FreeRequestBean;
import org.cometmi.gwt.shared.request.ListenRequestBean;
import org.cometmi.gwt.shared.request.PublishRequestBean;
import org.cometmi.gwt.shared.request.QueueRequestBean;
import org.cometmi.gwt.shared.request.ResponseStatus;

import com.google.gwt.user.client.rpc.SerializationException;

@SuppressWarnings("serial")
@WebServlet(name = "CometMiServiceServlet", urlPatterns = { "/cometmi.gwt/main" }, asyncSupported = true)
public class CometMiServiceImpl extends AsyncRemoteServiceServlet implements CometMiService
{
	static protected Logger logger = Logger.getLogger(CometMiServiceImpl.class);

	/**
	 * Publishes a method invocation request.
	 * 
	 * @param publishRequest The request.
	 */
	@Override
	public ResponseStatus publish(PublishRequestBean publishRequest)
	{
		logger.debug("[CometMiServiceServlet] publishing queue: " + publishRequest.getQueueExpression());

		ServletContext appScope = getThreadLocalRequest().getServletContext();
		MiBox miBox = (MiBox) appScope.getAttribute(MiBox.class.getName());

		try
		{
			miBox.publish(publishRequest.getQueueExpression(), publishRequest.getCalls());
			return ResponseStatus.Success;
		}
		catch (Throwable e)
		{
			logger.error("[CometMiServiceServlet] error while publishing:", e);
			return ResponseStatus.Unknown;
		}
	}

	/**
	 * Publish a listen request, and attaches a {@link AsyncManager} to a
	 * {@link DeferredPoller}, in this way when available new elements on the
	 * chosen queue, they will be pushed.
	 * 
	 * @param listenRequest The request
	 * @param asyncManager The async manager.
	 * @throws NameParseException
	 */
	public void listen(ListenRequestBean listenRequest, final AsyncManager<List<Call>> asyncManager)
			throws NameParseException
	{
		logger.debug("[CometMiServiceServlet] listening on queue:" + listenRequest.getQueueName());

		ServletContext appScope = getThreadLocalRequest().getServletContext();
		MiBox miBox = (MiBox) appScope.getAttribute(MiBox.class.getName());

		/* No timeout will be provided */
		asyncManager.setTimeout(0);

		try
		{
			try
			{
				final String queueName = listenRequest.getQueueName();

				miBox.poll(queueName, new DeferredPoller()
				{
					@Override
					public void onPoll(List<Call> elems) throws SerializationException, IOException
					{
						asyncManager.doCompleteForSuccess(elems);
					}

					@Override
					public boolean isActive()
					{
						return asyncManager.isActive();
					}
				});
			}
			catch (IOException e)
			{
				asyncManager.doCompleteForFailure(new Exception("Io exception: " + e.getLocalizedMessage()));

				logger.error("[CometMiServiceServlet] error while listening:", e);
			}
			catch (SerializationException e)
			{
				asyncManager.doCompleteForFailure(new Exception("Serialization exception: " + e.getLocalizedMessage()));
				logger.error("[CometMiServiceServlet] error while listening:", e);
			}
		}
		catch (Throwable e1)
		{
			logger.error("[CometMiServiceServlet] error while listening:", e1);
		}
	}

	/**
	 * This method is unused because wrapped by the async version.
	 */
	@Override
	public List<Call> listen(ListenRequestBean listenRequest)
	{
		return null;
	}

	@Override
	public void freeQueue(FreeRequestBean freeRequest)
	{
		logger.debug("[CometMiServiceServlet] attempting to free the queue " + freeRequest.getQueueName());

		ServletContext appScope = getThreadLocalRequest().getServletContext();
		MiBox miBox = (MiBox) appScope.getAttribute(MiBox.class.getName());

		try
		{
			miBox.freeQueue(freeRequest.getQueueName(), freeRequest.isDiscard());
		}
		catch (Throwable e)
		{
			logger.debug("[CometMiServiceServlet] error while attempting to free the queue "
					+ freeRequest.getQueueName());
		}
	}

	@Override
	public ResponseStatus checkQueueAvailability(QueueRequestBean queueRequest)
	{
		logger.debug("[CometMiServiceServlet] checking availability of queue:" + queueRequest.getQueueName());

		ServletContext appScope = getThreadLocalRequest().getServletContext();
		MiBox miBox = (MiBox) appScope.getAttribute(MiBox.class.getName());

		synchronized (CometMiServiceImpl.class)
		{
			if (miBox.setCredentialsForQueue(queueRequest.getQueueName(), queueRequest.getCredentials(),
					queueRequest.getAttributes()))
				return ResponseStatus.Success;
			else
				return ResponseStatus.QueueAlreadyBound;
		}
	}

	@Override
	public void setQueueAttribute(String queueName, String key, String value)
	{
		logger.debug("[CometMiServiceServlet] adding attribute (" + key + ": " + value + ") to queue " + queueName);

		ServletContext appScope = getThreadLocalRequest().getServletContext();
		MiBox miBox = (MiBox) appScope.getAttribute(MiBox.class.getName());

		miBox.setQueueAttribute(queueName, key, value);
	}

	@Override
	public String getQueueAttribute(String queueName, String key)
	{
		logger.debug("[CometMiServiceServlet] getting attribute (" + key + ") to queue " + queueName);

		ServletContext appScope = getThreadLocalRequest().getServletContext();
		MiBox miBox = (MiBox) appScope.getAttribute(MiBox.class.getName());

		return miBox.getQueueAttribute(queueName, key);
	}

	@Override
	public String removeQueueAttribute(String queueName, String key)
	{
		logger.debug("[CometMiServiceServlet] removing attribute (" + key + ") to queue " + queueName);

		ServletContext appScope = getThreadLocalRequest().getServletContext();
		MiBox miBox = (MiBox) appScope.getAttribute(MiBox.class.getName());

		return miBox.removeQueueAttribute(queueName, key);
	}

	@Override
	public void checkConnection()
	{
		logger.error("[CometMiServiceServlet] Checking the connection");
	}
}
